package com.modules.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.modules.entity.Applicantion;
import com.modules.entity.ApplicantionDao;
import com.modules.entity.LicenseCreatorParam;
import com.modules.entity.User;
import com.modules.entity.UserDao;
import com.modules.license.*;
import com.nfschina.platform.system.license.entity.LicenseCheckModel;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletResponse;

/**
 *
 * 用于生成证书文件，不能放在给客户部署的代码里
 * @since 1.0.0
 */
@RestController
@RequestMapping("/license")
public class LicenseCreatorController {

    @Autowired
    private UserDao userDao;
    
    @Autowired
    private ApplicantionDao applicantionDao;
    /**
     * 证书生成路径
     */
    @Value("${license.licensePath}")
    private String licensePath;

    /**
     * 获取服务器硬件信息
     * @param osName 操作系统类型，如果为空则自动判断
     * @return com.ccx.models.license.LicenseCheckModel
     */
    @RequestMapping(value = "/getServerInfos",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public LicenseCheckModel getServerInfos(@RequestParam(value = "osName",required = false) String osName) {
        //操作系统类型
        if(StringUtils.isBlank(osName)){
            osName = System.getProperty("os.name");
        }
        osName = osName.toLowerCase();

        AbstractServerInfos abstractServerInfos = null;

        //根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        } else if (osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        }else{//其他服务器类型
            abstractServerInfos = new LinuxServerInfos();
        }
        return abstractServerInfos.getServerInfos();
    }

    /**
     * 生成证书
     * @param param 生成证书需要的参数，如：{"subject":"ccx-models","privateAlias":"privateKey","keyPass":"5T7Zz5Y0dJFcqTxvzkH5LDGJJSGMzQ","storePass":"3538cef8e7","licensePath":"C:/Users/zifangsky/Desktop/license.lic","privateKeysStorePath":"C:/Users/zifangsky/Desktop/privateKeys.keystore","issuedTime":"2018-04-26 14:48:12","expiryTime":"2018-12-31 00:00:00","consumerType":"User","consumerAmount":1,"description":"这是证书描述信息","licenseCheckModel":{"ipAddress":["192.168.245.1","10.0.5.22"],"macAddress":["00-50-56-C0-00-01","50-7B-9D-F9-18-41"],"cpuSerial":"BFEBFBFF000406E3","mainBoardSerial":"L1HF65E00X9"}}
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @RequestMapping(value = "/generateLicense",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Map<String,Object> generateLicense(@RequestBody LicenseCreatorParam param) {
        Map<String,Object> resultMap = new HashMap<>(2);

        if(StringUtils.isBlank(param.getLicensePath())){
            param.setLicensePath(licensePath);
        }

        LicenseCreator licenseCreator = new LicenseCreator(param);
        boolean result = licenseCreator.generateLicense();

        if(result){
            resultMap.put("result","ok");
            resultMap.put("msg",param);
        }else{
            resultMap.put("result","error");
            resultMap.put("msg","证书文件生成失败！");
        }
        return resultMap;
    }
    @CrossOrigin
    @RequestMapping(value = "/downLoadLicense/{id}",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void downLoadLicense(HttpServletResponse response, @PathVariable("id") Long id) {
        Map<String,Object> resultMap = new HashMap<>(2);

        if(id!=null){
        	Optional<Applicantion> query = applicantionDao.findById(id);
        	if (query.isPresent()) {
        		Applicantion applicantion = query.get();
//        		String sy ="{\"cpuSerial\":\"BFEBFBFF000A0655\",\"ipAddress\":[\"192.168.162.100\",\"2400:dd01:100f:5f92:6441:9dba:88e2:387d\",\"2400:dd01:100f:5f92:2197:db60:6fe:b279\",\"2400:dd01:100f:5f92:34ee:73dc:43e2:fcef\",\"2400:dd01:100f:5f92:3c10:6e44:69bd:58d6\",\"2400:dd01:100f:5f92:7478:d546:1b77:7e79\",\"2400:dd01:100f:5f92:fcdd:a4ab:691f:a796\"],\"macAddress\":[\"70-B5-E8-67-DF-C8\"],\"mainBoardSerial\":\"/FPJTRD3/CNWS20014300TN/\"}";
//            	LicenseCheckModel model = JSONObject.toJavaObject(JSON.parseObject(sy),LicenseCheckModel.class
//            			);
            	LicenseCheckModel model = new LicenseCheckModel();
            	List<String> macAddressList = new ArrayList<String>();
            	if(applicantion.getMacAddress()!=null&&applicantion.getMacAddress().length()>0) {
	            	macAddressList.add(applicantion.getMacAddress());
					model.setMacAddress(macAddressList );
            	}
            	model.setModule("gateway,auth,system,docReview");
            	LicenseCreatorParam param = new LicenseCreatorParam();
            	param.setSubject("nfsplatform");
            	param.setPrivateAlias("privateKey");
            	param.setKeyPass("123456ab");
            	param.setStorePass("123456ab");
            	param.setLicensePath("test.lic");
            	param.setPrivateKeysStorePath("D:/keytest/privateKeys.keystore");
            	param.setIssuedTime(applicantion.getIssuedTime());
            	param.setExpiryTime(applicantion.getExpiryTime() );
            	param.setConsumerType("User");
            	param.setConsumerAmount(1);
            	param.setDescription("");
            	param.setLicenseCheckModel(model);
                LicenseCreator licenseCreator = new LicenseCreator(param);
                boolean result = licenseCreator.generateLicense();

                if(result){
                	File file = new File("test.lic");

                    String filename = file.getName();
                    byte[] buffer = new byte[(int) file.length()];
//                    BufferedInputStream bis = null;
                    FileInputStream is = null;
                    OutputStream os = null;
                    try {
                        //文件是否存在
                        if (file.exists()) {
                            //设置响应
                            response.setContentType("application/octet-stream;charset=UTF-8");
                            // 将响应头中的Content-Disposition暴露出来，不然前端获取不到
                            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
                            // 在响应头中的Content-Disposition里设置文件名称
                            response.setHeader("Content-Disposition","attachment;filename="+filename);
                            os = response.getOutputStream();
                            is = new FileInputStream(file);
                            while(is.read(buffer) != -1){
                                os.write(buffer);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if(is != null) {
                                is.close();
                            }
                            if(os != null) {
                                os.flush();
                                os.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    resultMap.put("result","ok");
                    resultMap.put("msg",param);
                }else{
                	
                }
			}
        }


    }
    
    @RequestMapping(value = "/testUserDao",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Map<String,Object> testUserDao(@RequestParam(value = "osName",required = false) String osName) {
        Map<String,Object> resultMap = new HashMap<>(2);
        userDao.save(new User(11L, "jack", "123"));
        return resultMap;
    }
    
    @RequestMapping(value = "/addApplicantion",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Map<String,Object> addApplicantion(@RequestBody Applicantion applicantion) {
        Map<String,Object> resultMap = new HashMap<>(2);
        try {
        	applicantionDao.save(applicantion);

            resultMap.put("result","ok");
            resultMap.put("msg",applicantion);
        }catch (Exception e) {
            resultMap.put("result","error");
            resultMap.put("msg","保存申请失败！");
        }
        return resultMap;
    }

    @RequestMapping(value = "/dealApplicantion",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Map<String,Object> dealApplicantion(@RequestBody Applicantion param) {
        Map<String,Object> resultMap = new HashMap<>(2);
        try {
            if(param!=null){
            	Optional<Applicantion> query = applicantionDao.findById(param.getId());
            	if (query.isPresent()) {

            		Applicantion applicantion = query.get();
            		applicantion.setState(param.getState());
            		applicantionDao.save(applicantion);
            		resultMap.put("result","ok");
            		resultMap.put("msg",applicantion);
            	}
            }
        }catch (Exception e) {
            resultMap.put("result","error");
            resultMap.put("msg","保存申请失败！");
        }
        return resultMap;
    }
    @RequestMapping(value = "/listApplicantion",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Map<String,Object> listApplicantion(@RequestBody Applicantion applicantion) {
        Map<String,Object> resultMap = new HashMap<>(2);
        try {
        	List<Applicantion> rows = applicantionDao.findAll(Sort.by(Direction.DESC, "id"));

            resultMap.put("rows",rows);
            resultMap.put("msg","ok");
        }catch (Exception e) {
            resultMap.put("result","error");
            resultMap.put("msg","保存申请失败！");
        }
        return resultMap;
    }

    @RequestMapping(value = "/listPassApplicantion",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Map<String,Object> listPassApplicantion(@RequestBody Applicantion applicantion) {
        Map<String,Object> resultMap = new HashMap<>(2);
        try {
        	List<Applicantion> rows = applicantionDao.findByState("true", Sort.by(Direction.DESC, "id"));

            resultMap.put("rows",rows);
            resultMap.put("msg","ok");
        }catch (Exception e) {
            resultMap.put("result","error");
            resultMap.put("msg","保存申请失败！");
        }
        return resultMap;
    }
    public static void main1(String[] args) throws ParseException {
    	String osName ="windows";
		if(StringUtils.isBlank(osName )){
            osName = System.getProperty("os.name");
        }
        osName = osName.toLowerCase();

        AbstractServerInfos abstractServerInfos = null;

        //根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        } else if (osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        }else{//其他服务器类型
            abstractServerInfos = new LinuxServerInfos();
        }
        System.out.println( JSON.toJSONString(abstractServerInfos.getServerInfos() ));
    }
    
    public static void main(String[] args) throws ParseException {
//    	LicenseCheckModel model = new LicenseCheckModel();
//    	model.setCpuSerial("BFEBFBFF000206A7");
//    	model.setMainBoardSerial("");
//    	List<String> macAddress = new WindowsServerInfos().getServerInfos().getMacAddress();
//    	model.setMacAddress(macAddress);
//    	model.setModule("gateway,auth,system,docReview");
    	String sy ="{\"cpuSerial\":\"BFEBFBFF000A0655\",\"ipAddress\":[\"192.168.162.100\",\"2400:dd01:100f:5f92:6441:9dba:88e2:387d\",\"2400:dd01:100f:5f92:109b:a3f8:8e7d:d095\",\"2400:dd01:100f:5f92:45db:23b2:14a4:ebe3\",\"2400:dd01:100f:5f92:48c9:f825:3536:8f9d\",\"2400:dd01:100f:5f92:88f6:49a2:efde:e4f4\",\"2400:dd01:100f:5f92:c402:c42e:821b:ea3a\",\"2400:dd01:100f:5f92:cc4c:b5ba:ebb6:9d58\",\"2400:dd01:100f:5f92:dd42:40d9:f9ab:57ab\"],\"macAddress\":[\"70-B5-E8-67-DF-C8\"],\"mainBoardSerial\":\"/FPJTRD3/CNWS20014300TN/\"}";
    	LicenseCheckModel model = JSONObject.toJavaObject(JSON.parseObject(sy),LicenseCheckModel.class
    			);
    	model.setModule("gateway,auth,system,docReview");
    	LicenseCreatorParam param = new LicenseCreatorParam();
    	param.setSubject("nfsplatform");
    	param.setPrivateAlias("privateKey");
    	param.setKeyPass("123456ab");
    	param.setStorePass("123456ab");
    	param.setLicensePath("C:/lic/100.lic");
    	param.setPrivateKeysStorePath("C:/spring-boot2-license/keytest/privateKeys.keystore");
    	param.setIssuedTime(new SimpleDateFormat("yyyy/MM/dd").parse("2021/07/10")  );
    	param.setExpiryTime(new SimpleDateFormat("yyyy/MM/dd").parse("2025/07/10")  );
    	param.setConsumerType("User");
    	param.setConsumerAmount(1);
    	param.setDescription("");
    	param.setLicenseCheckModel(model);
        LicenseCreator licenseCreator = new LicenseCreator(param);
        boolean result = licenseCreator.generateLicense();

	}
}
